package com.margo.project.redis.script.action;

import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * redis简单限流   计数器法
 * @author fangxingbang
 *
 */
@RestController
public class RedisLimitController {
	
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	
	/**
	 * localhost:8080/limit/redis/request
	 * @return
	 */
	@RequestMapping(path="/limit/redis//request")
	private String redis() {
		String result=null;
		List<String> keys=new LinkedList<String>();
		keys.add("limit:20210406:request");
		DefaultRedisScript<Long> script=new DefaultRedisScript<Long>("if(redis.call('exists',KEYS[1])==1) then\r\n" + 
				"	if(redis.call('get',KEYS[1])>ARGV[1]) then\r\n" + 
				"		return 1;\r\n" + 
				"	else\r\n" + 
				"		redis.call('incr',KEYS[1]);\r\n" + 
				"	end;\r\n" + 
				"else\r\n" + 
				"	redis.call('set',KEYS[1],1);\r\n" + 
				"	redis.call('expire',KEYS[1],2);\r\n" + 
				"end;\r\n" + 
				"return 2;",Long.class);
		script.setResultType(Long.class);
		Long scriptResult=stringRedisTemplate.execute(script, keys, "5");
		logger.info("script:result:"+scriptResult.toString());
		if(Integer.valueOf(scriptResult.toString())==1) {
			result="fail with limit";
		}else {
			result="success";
		}
		return result;
	}

}
